package org.goodsmanager.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 性能监控切面
 *
 * @author Goods Manager System
 * @version 1.0.0
 */
@Slf4j
@Aspect
@Component
public class PerformanceMonitorAspect {

    /**
     * 监控Service层方法执行时间
     */
    @Around("execution(* org.goodsmanager.service.*.*(..))")
    public Object monitorServicePerformance(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        
        try {
            Object result = joinPoint.proceed();
            long endTime = System.currentTimeMillis();
            long executionTime = endTime - startTime;
            
            // 记录执行时间超过500ms的方法
            if (executionTime > 500) {
                log.warn("Service方法执行耗时较长: {}.{} 执行时间: {}ms", 
                        className, methodName, executionTime);
            } else {
                log.debug("Service方法执行: {}.{} 执行时间: {}ms", 
                        className, methodName, executionTime);
            }
            
            return result;
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            long executionTime = endTime - startTime;
            log.error("Service方法执行异常: {}.{} 执行时间: {}ms 异常: {}", 
                    className, methodName, executionTime, e.getMessage());
            throw e;
        }
    }
}